package xyz.weblade.beans.factory.support;

import xyz.weblade.beans.BeansException;
import xyz.weblade.beans.factory.BeanFactory;
import xyz.weblade.beans.factory.FactoryBean;
import xyz.weblade.beans.factory.config.BeanDefinition;
import xyz.weblade.beans.factory.config.BeanPostProcessor;
import xyz.weblade.beans.factory.config.ConfigurableBeanFactory;
import xyz.weblade.core.convert.ConversionService;
import xyz.weblade.util.ClassUtils;
import xyz.weblade.util.StringValueResolver;

import java.util.ArrayList;
import java.util.List;

/**
 * BeanFactory的最基础的抽象类，定义了getBeans的模板方法
 */
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {

    private ConversionService conversionService;
    private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();

    //embedded 嵌入式 值解析器
    private final List<StringValueResolver> embeddedValueResolvers = new ArrayList<>();

    public void addEmbeddedValueResolver(StringValueResolver valueResolver) {
        this.embeddedValueResolvers.add(valueResolver);
    }

    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name, null);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name, args);
    }
    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return (T) getBean(name);
    }
    protected <T> T doGetBean(final String name, final Object[] args) {
        Object sharedInstance = getSingleton(name);
        //如果已经在单例池，就直接拿单例池（不需要线程安全，因为不是并发写入），但如果这个对象是一个FactoryBean，就直接去factoryBeanObjectCache（线程安全，因为可能会频繁的创建跟销毁）里拿
        if (sharedInstance != null) {
            return (T) getObjectForBeanInstance(sharedInstance, name);
        }

        BeanDefinition beanDefinition = getBeanDefinition(name);
        //正常创建流程
        Object bean = createBean(name, beanDefinition, args);
        return (T)getObjectForBeanInstance(bean,name);
    }
    private Object  getObjectForBeanInstance(Object beanInstance, String beanName) {
        if (!(beanInstance instanceof FactoryBean)) {
            return beanInstance;
        }

        Object object = getCachedObjectForFactoryBean(beanName);

        if (object == null) {
            //第一次IUserDao进来，只是一个代理类，而且还不是FactoryBean的
            FactoryBean<?> factoryBean = (FactoryBean<?>) beanInstance;
            object = getObjectFromFactoryBean(factoryBean, beanName);
        }

        return object;
    }

    protected abstract BeanDefinition getBeanDefinition(String name) throws  BeansException;

    protected  abstract  Object createBean(String beanName,BeanDefinition beanDefinition,Object[] args) throws BeansException;

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    public List<BeanPostProcessor> getBeanPostProcessors() {
        return this.beanPostProcessors;
    }

    public ClassLoader getBeanClassLoader() {
        return this.beanClassLoader;
    }

    /**
     * 翻译的具体实现
     */
    public String resolveEmbeddedValue(String value) {
        String result = value;
        for (StringValueResolver resolver : this.embeddedValueResolvers) {
            result = resolver.resolveStringValue(result);
        }
        return result;
    }

    @Override
    public void setConversionService(ConversionService conversionService) {
        this.conversionService = conversionService;
    }

    @Override
    public ConversionService getConversionService() {
        return conversionService;
    }
}
